# coding=utf-8

from flask import render_template, url_for, redirect, flash, abort, request
from flask_login import current_user, login_required
from ..model import User, Room, Notice
from ..forms import Userform, Create_Notice_form, Create_Room_form
from . import TCview

@login_required
@TCview.route('/room', methods=['GET', 'POST'])
def index():
    """Index page

    list rooms.
    User can choose their room.

    """
    Flag = False
    if current_user.Room_Id is None:
        Flag = True
    R = Room.objects().all()
    return render_template("/room/index.html", Flag=Flag, R=R)

@login_required
@TCview.route('/room/add/<int:User_Id>/<int:Room_Id>')
def add_room(User_Id, Room_Id):
    R = Room.objects(Id=Room_Id).first()
    U = User.objects(Id=User_Id).first()
    if R is None:
        abort(404)
    if U is None:
        abort(404)
    
    try:
        U.update(Room_Id=Room_Id)
        R.Number_list.append(User_Id)
    except:
        flash('save fail')

    return redirect( url_for('room', Id=Room_Id) )

@login_required
@TCview.route('/room/<int:Id>', methods=['GET', 'POST'])
def room(Id):
    """Room's page

    Show room's members and their last Notice.
    check port.

    """
    R = Room.objects(Id=Id).first()
    if R is None:
        abort(404)
    K = []
    for i in R.Number_list:
        U = User.objects(Id=i).first()
        number = U.Notice_list.max()
        N = Notice.objects(Id=number).first()
        K.append({
            'name' : U.Name,
            'date' : N.Date,
            'Nearly': N.Content
        })

    return render_template('/room/room.html', title=R.Name, Introduction=R.Introduction, K=K)

@login_required
@TCview.route('/room/<int:Id>/check')
def room_check(Id):
    """Check room's member's work

    /room/<int:Id>/check?min= ,max=

    Args:
        Id : Room's ID
        min , max : check the day between min and max

    Returns:
        D : the table of mumber's notices

    """

    R = Room.objects(Id=Id).first()
    if R is None:
        abort(404)

    mi = request.args.get('min')
    mx = request.args.get('max')

    K = []
    D = {}
    for i in R.Number_list:
        U = User.objects(Id=i).first()
        K.append({
            'Id':i,
            'name':U.name
        })
        l = U.Notice_list
        l.sort()
        for j in l:
            n = Notice.objects(Id=j).first()
            if n.Date <= mx and n.Date >= mi:
                if n.Date not in D.keys():
                    D[n.Date] = {}
                    D[n.Date][U.name] = n.Content
                else:
                    D[n.Date][U.name] = n.Content

    return render_template('/room/check.html', title=R.Name, D=D)

@login_required
@TCview.route('/create/room', methods=['GET', 'POST'])
def create_room():
    F = Create_Room_form()
    if F.validate_on_submit():
        Id = Room.objects().count()+1
        R = Room(Id=Id, Name=F.name.data, Introduction=F.Introduction.data)
        R.save()
        flash('Success create room')
        return redirect(url_for('TCview.index'))
    return render_template('/create.html', title='Room', F=F)

@login_required
@TCview.route('/create/notice', methods=['GET', 'POST'])
def create_notice():
    F = Create_Notice_form()
    if F.validate_on_submit():
        Id = Notice.objects().count()+1
        N = Notice(Id=Id, User_Id=current_user.Id, Date=F.Date.date, Content=F.Introduction.data)
        N.save()
        U = User.objects(Id=current_user.Id).first()
        U.Notice_list.append(Id)
        U.update()
        return redirect(url_for('TCview.user', Id=current_user.Id))
    return render_template('/create.html', title='Notice', F=F)

@login_required
@TCview.route('/change/room', methods=['GET', 'POST'])
def change_room():
    Id = request.args.get('Id')

    R = Room.objects(Id=Id).first()
    if R is None:
        abort(404)

    F = Create_Room_form()

    if F.validate_on_submit():
        R.update(Name=F.name.data, Introduction=F.Introduction.data)
        return  redirect(url_for('TCview.room', Id=Id))

    F.name.data = R.Name
    F.Introduction.data = R.Introduction

    return render_template('/create.html', title='Room', F=F)

@login_required
@TCview.route('/change/notice', methods=['GET', 'POST'])
def change_notice():
    Id = request.args.get('Id')

    N = Notice.objects(Id=Id).first()
    if N is None:
        abort(404)
    if N.User_Id != current_user.Id:
        abort(403)

    F = Create_Notice_form()
    if F.validate_on_submit():
        N.update(Date=F.Date.data, Introduction=F.Introduction.data)
        flash('Success Change Notice')
        return redirect(url_for('TCview.user', Id=current_user.Id))

    F.Introduction.data = N.Introduction
    F.Date = N.Date

    return render_template('/create.html', title='Notice', F=F)

@login_required
@TCview.route('/user', methods=['GET', 'POST'])
def user():
    Id = request.args.get('Id')

    U = User.objects(Id=Id).first()
    if U is None:
        abort(404)

    Flag = False
    if Id == current_user.Id:
        Flag = True

    D = {}
    for i in U.Notice_list:
        N = Notice.objects(Id=i).first()
        D[N.Date] = N.Introduction

    return render_template('user.html', Flag=Flag, D=D, user=current_user.name)

@login_required
@TCview.route('/delete/room')
def delete_room():
    Id = request.args.get('Id')

    R = Room.objects(Id=Id).first()
    if R is None:
        abort(404)

    for i in R.Number_list:
        U = User.objects(Id=i).first()
        U.update(Room_Id=None)

    R.delete()
    flash('delete success')
    return redirect(url_for('TCview.index'))

@login_required
@TCview.route('/delete/notice')
def delete_notice():
    Id = request.args.get('Id')

    N = Notice.objects(Id=Id).first()
    if N is None:
        abort(404)
    if N.User_Id != current_user.Id:
        abort(403)

    U = User.objects(Id=current_user.Id).first()
    U.Notice_list.remove(Id)
    U.update()

    N.delete()
    flash('delete success!')

    return redirect(url_for('TCview.user', Id=current_user.Id))
